package com.hu.uitl;

import java.io.*;
import java.net.*;
import java.nio.channels.FileChannel;

public class FileUtils {

    public static void main(String[] args) {
        String url = "http://img.netbian.com/file/2017/0713/bb096e7fc133ddfbe1d409cf9340800b.jpg";
        try {
            random(url, "E:\\1.jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件复制
     *
     * @param s 源文件 如 D:\\c.txt
     * @param t 目标文件或目录 如D:\\或D:\\d.txt
     */
    public static void Copy(String s, String t) {
        File source = new File(s);
        File target = new File(t);
        if (target.exists()) {
            target = new File(target + source.getName());
        }
        FileChannel in = null;
        FileChannel out = null;
        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        try {
            inStream = new FileInputStream(source);
            outStream = new FileOutputStream(target);
            in = inStream.getChannel();
            out = outStream.getChannel();
            in.transferTo(0, in.size(), out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
                in.close();
                outStream.close();
                out.close();
            } catch (IOException e) {
                //忽略关闭异常
            }
        }
    }

    /**
     * 生成文件名
     *
     * @param src 文件的路径如 E:\\a.jpg 生成150....jpg
     * @return
     */
    public static String getName(String src) {
        int l = src.lastIndexOf(".");
        String k = src.substring(l, src.length());
        long n = System.currentTimeMillis();
        return n + k;
    }

    /**
     * 下载网络文件
     *
     * @param urls 文件的url 如http://img.netbian.com/file/2017/0607/065f5dfcbff6dfe9671775ce8e7807af.jpg
     * @param tar  存储的目录 如E:\\
     */
    public static void down(String urls, String tar) {
        //   int bytesum = 0;//记录文件下载进度
        int byteread = 0;
        try {
            URL url = new URL(urls);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            String name = getName(urls);
            FileOutputStream fs = new FileOutputStream(tar + name);
            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
//                bytesum += byteread;//打印文件下载的进度
//                System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 断点下载
     * url 网络文件的url
     * savePath 文件下载保存的路径
     */
    static void random(String url, String savePath) throws IOException {
        int bytesum = 0;
        // 打开连接
        URLConnection con = new URL(url).openConnection();
        HttpURLConnection conn = (HttpURLConnection) con;
        long localFileSize = 0;
        File file = new File(savePath);

        long remoteFileSize = conn.getContentLength(); // 获得远程文件大小
        int i = 0;
        if (file.exists()) {
            localFileSize = file.length(); // 获得本地文件大小
            if (localFileSize < remoteFileSize) {
                System.out.println("文件续传");
                conn.setRequestProperty("User-Agent", "NetFox"); // 设置User-Agent
                conn.setRequestProperty("Range", "bytes=" + localFileSize + "-" + remoteFileSize);// 设置断点续传的开始位置
                InputStream input = con.getInputStream(); // 获得输入流
                RandomAccessFile oSavedFile = new RandomAccessFile(savePath, "rw");
                oSavedFile.seek(localFileSize);// 定位文件指针到nPos位置
                byte[] b = new byte[1024];
                int nRead;
                // 从输入流中读入字节流，然后写到文件中
                while ((nRead = input.read(b, 0, 1024)) > 0) {
                    bytesum += nRead;
                    System.out.println(bytesum);
                    (oSavedFile).write(b, 0, nRead);
                }
                conn.disconnect();
                input.close();

            } else {
                System.out.println("文件已经下载好了");
            }
        } else {
                file.createNewFile();
                System.out.println("下载中");
                InputStream input = conn.getInputStream();
                RandomAccessFile oSavedFile = new RandomAccessFile(savePath, "rw");
                oSavedFile.seek(localFileSize);
                byte[] b = new byte[1024];
                int nRead;
                while ((nRead = input.read(b)) != -1) {
//                    bytesum +=nRead;
//                    System.out.println(bytesum);打印下载进度
                    (oSavedFile).write(b, 0, nRead);
                }
                System.out.println("下载完成");
                conn.disconnect();
        }


    }

}
